
import javafx.util.Pair;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2025-08-02
 * Time: 22:58
 */
public class Test76 {
    public static int[] topKFrequent(int[] num, int k) {
        Map<Integer,Integer> hash = new HashMap<>();
        // key -> 元素  value -> 次数
        for(int x : num) {
            hash.put(x,hash.getOrDefault(x,0)+1);
        }

        PriorityQueue<Pair<Integer,Integer>> q = new PriorityQueue<>((a,b)->{
            return a.getValue()-b.getValue();
        });

        for(Map.Entry<Integer,Integer> e : hash.entrySet()) {
            q.offer(new Pair<>(e.getKey(),e.getValue()));
            if(q.size() > k) {
                q.poll();
            }
        }


        int[] ret = new int[k];
        int i = k-1;
        while(!q.isEmpty()) {
            ret[i] = q.poll().getKey();
            i--;
            if(i < 0) {
                break;
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        int[] num = {1,1,1,2,2,3};
        int k = 2;
        int[] ret = topKFrequent(num,k);
        System.out.println(Arrays.toString(ret));
    }
}
